import React, { memo, useEffect } from 'react'
import type { FC, ReactNode } from 'react'

import { SongDetailWrapper } from './style'
import { useLocation } from 'react-router-dom'
import {
  fetchSongDetailAction,
  fetchSongSimiAction
} from '@/store/modules/song'
import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store'
import SongInfo from './c-cnps/songInfo'
import { fetchByIdGetLyricAction, fetchByIdGetSongDetailAction } from '@/store/modules/audio'
import Comment from './c-cnps/comment'

interface IProps {
  children?: ReactNode
}

const SongDetail: FC<IProps> = () => {
  const location = useLocation()
  const dispath = useAppDispatch()

  // 获得上一个页面的参数，获取歌曲id
  const searchParams = new URLSearchParams(location.search)
  const id = searchParams.get('id')

  useEffect(() => {
    // 发起歌曲详情的请求
    dispath(fetchSongDetailAction(Number(id)))
    // 获得歌词
    dispath(fetchByIdGetLyricAction(id))
    // 获得相似歌曲
    dispath(fetchSongSimiAction(Number(id)))
  }, [id])
  // 获得歌曲详情
  const { songDetail, lyricList, similarSongList } = useAppSelector(
    (state) => ({
      songDetail: state.songDetail.songDetail,
      lyricList: state.audio.lyricList,
      similarSongList: state.songDetail.similarSongList
    }),
    shallowEqualApp
  )

  // 播放歌曲
  const playSong = (id: number) => {
    dispath(fetchByIdGetSongDetailAction(id))
  }

  // 渲染相似歌曲
  const renderSimiSong = () => {
    return (
      similarSongList?.length &&
      similarSongList.map((item) => {
        return (
          <div className="simi_item" key={item.id}>
            <div className="simi_left">
              <span>{item?.name}</span>
              <span>{item?.artists[0]?.name}</span>
            </div>
            <div className="simi_right">
              <a className="sprite_icon3 play" onClick={() => playSong(item.id)}></a>
              <a className="sprite_icon3 favor"></a>
            </div>
          </div>
        )
      })
    )
  }

  return (
    <SongDetailWrapper>
      <div className="left">
        {/* 歌曲信息 */}
        <SongInfo info={songDetail} lyricList={lyricList}></SongInfo>
        <Comment info={songDetail}></Comment>
      </div>
      <div className="right">
        <div className="simi_title">
          <span>相似歌曲</span>
        </div>
        {renderSimiSong()}
      </div>
    </SongDetailWrapper>
  )
}

export default memo(SongDetail)
